//C13:13.2:reducto.c -- reduce to 1/3.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#define LEN  40

int main(int argc, char *argv[])
{
	FILE *in, *out;
	int ch;

	char name[LEN];
	int count = 0;

	if(argc < 2)
	{
		fprintf(stderr, "Usage: %d filename, %s\n", argv[0], strerror(errno));
		exit(1);
	}

	if((in = fopen(argv[1], "r")) == NULL)
	{
		fprintf(stderr, "I couldn't open the file %s \"%s\"\n",
				strerror(errno),argv[1]);
		exit(1);
	}

	strcpy(name, argv[1]);
	strcat(name, ".red");
	if((out = fopen(name, "w")) == EOF)
	{
		fprintf(stderr, "Can't create output file. %s\n", strerror(errno));
		exit(3);
	}

	// copy data
	while ((ch = getc(in)) != EOF)
	{
		if(count++ % 3 == 0)
		{
			putc(ch, out);
		}
	}

	if(fclose(in) != 0 || fclose(out) != 0)
	{
		fprintf(stderr, "Error in closing files\n");
	}
}

